package com.xbongbong.paas.help;

import com.xbongbong.paas.constant.ConfigConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasUserEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.model.PaasUserModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CommonVisibleRangeTeamEntity;
import com.xbongbong.saas.domain.entity.ProductUserEntity;
import com.xbongbong.saas.domain.entity.UserAndDepTeamEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.WarehouseUserEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorUserEntity;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.model.BomUserModel;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.saas.model.CompetitorUserModel;
import com.xbongbong.saas.model.ContactUserModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.MarketActivityUserModel;
import com.xbongbong.saas.model.OpportunityUserModel;
import com.xbongbong.saas.model.PayBalanceUserModel;
import com.xbongbong.saas.model.PayPlanSheetUserModel;
import com.xbongbong.saas.model.PayPlanUserModel;
import com.xbongbong.saas.model.PaymentBalanceUserModel;
import com.xbongbong.saas.model.PaymentSheetUserModel;
import com.xbongbong.saas.model.PaymentUserModel;
import com.xbongbong.saas.model.ProductUserModel;
import com.xbongbong.saas.model.ProductionOrderUserModel;
import com.xbongbong.saas.model.PurchaseUserModel;
import com.xbongbong.saas.model.QuotationUserModel;
import com.xbongbong.saas.model.RefundUserModel;
import com.xbongbong.saas.model.SupplierContactUserModel;
import com.xbongbong.saas.model.SupplierUserModel;
import com.xbongbong.saas.model.WarehouseUserModel;
import com.xbongbong.saas.model.WorkOrderFlowUserModel;
import com.xbongbong.saas.model.team.UserAndDepTeamModel;
import com.xbongbong.saas.model.team.UserTeamModel;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author huguojun
 */
@Component
public class BusinessUserTeamHelp {

    private static final Logger LOG = LoggerFactory.getLogger(BusinessUserTeamHelp.class);

    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private OpportunityUserModel opportunityUserModel;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    private ContactUserModel contactUserModel;
    @Resource
    private SupplierUserModel supplierUserModel;
    @Resource
    private PurchaseUserModel purchaseUserModel;
    @Resource
    private BomUserModel bomUserModel;
    @Resource
    private ProductionOrderUserModel productionOrderUserModel;
    @Resource
    private PaymentUserModel paymentUserModel;
    @Resource
    private RefundUserModel refundUserModel;
    @Resource
    private PayPlanUserModel payPlanUserModel;
    @Resource
    private SupplierContactUserModel supplierContactUserModel;
    @Resource
    private ProductUserModel productUserModel;
    @Resource
    private QuotationUserModel quotationUserModel;
    @Resource
    private PaymentSheetUserModel paymentSheetUserModel;
    @Resource
    private PayPlanSheetUserModel payPlanSheetUserModel;
    @Resource
    private ClueUserModel clueUserModel;
    @Resource
    private MarketActivityUserModel marketActivityUserModel;
    @Resource
    private WorkOrderFlowUserModel workOrderFlowUserModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasUserModel paasUserModel;
    @Resource
    private PaymentBalanceUserModel paymentBalanceUserModel;
    @Resource
    private PayBalanceUserModel payBalanceUserModel;
    @Resource
    private WarehouseUserModel warehouseUserModel;
    @Resource
    private UserTeamModel userTeamModel;
    @Resource
    private UserAndDepTeamModel userAndDepTeamModel;

    @Resource
    private CompetitorUserModel competitorUserModel;
    /**
     *
     * @param dataIdList
     * @param corpid
     * @param businessType
     * @param isPublic
     * @return
     */
    public List<UserTeamEntity> getUserTeamList (List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic) {
        return getUserTeamList(dataIdList, corpid, businessType, isPublic, DelEnum.NORMAL.getDel());
    }

    public List<UserTeamEntity> getUserTeamList (List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Integer del) {
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        //沙雕公海客户，公海客户列表需要查询del=-1的前负责人数据
        map.put("del", isPublic ? -1 : del);
        return getUserTeamListByParams(dataIdList, businessType, map);
    }

    public List<UserTeamEntity> getUserTeamList (List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, List<Integer> del) {
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        //沙雕公海客户，公海客户列表需要查询del=-1的前负责人数据
        map.put("delIn", isPublic ? Collections.singletonList(-1) : del);
        return getUserTeamListByParams(dataIdList, businessType, map);
    }


    /**
     *
     * @param dataIdList
     * @param businessType
     * @return
     */

    public List<UserTeamEntity> getUserTeamListByParams (List<Long> dataIdList,  Integer businessType, Map<String, Object> map) {
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        List<UserTeamEntity> userTeamEntityList = new ArrayList<>();
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
            case DISTRIBUTOR_TEAM:
                map.put("customerIdIn", dataIdList);
                userTeamEntityList = customerUserModel.findBaseEntitys(map);
                break;
            case OPPORTUNITY_TEAM:
                map.put("opportunityIdIn", dataIdList);
                userTeamEntityList = opportunityUserModel.findBaseEntitys(map);
                break;
            case QUOTATION_TEAM:
                map.put("quotationIdIn", dataIdList);
                userTeamEntityList = quotationUserModel.findBaseEntitys(map);
                break;
            case CONTRACT_TEAM:
            case ORDER_TEAM:
                map.put("contractIdIn", dataIdList);
                userTeamEntityList = contractUserModel.findBaseEntitys(map);
                break;
            case SUPPLIER_TEAM:
                map.put("supplierIdIn", dataIdList);
                userTeamEntityList = supplierUserModel.findBaseEntitys(map);
                break;
            case SUPPLIER_CONTACT_TEAM:
                map.put("contactIdIn", dataIdList);
                userTeamEntityList = supplierContactUserModel.findBaseEntitys(map);
                break;
            case PAYMENT_TEAM:
                map.put("paymentIdIn", dataIdList);
                userTeamEntityList = paymentUserModel.findBaseEntitys(map);
                break;
            case PURCHASE_TEAM:
                map.put("purchaseIdIn", dataIdList);
                userTeamEntityList = purchaseUserModel.findBaseEntitys(map);
                break;
            case BOMBILL_TEAM:
                map.put("bomIdIn", dataIdList);
                userTeamEntityList = bomUserModel.findBaseEntitys(map);
                break;
            case PRODUCTIONORDER_TEAM:
                map.put("productionOrderIdIn", dataIdList);
                userTeamEntityList = productionOrderUserModel.findBaseEntitys(map);
                break;
            case CONTACT_TEAM:
            case DISTRIBUTOR_CONTACT_TEAM:
                map.put("contactIdIn", dataIdList);
                userTeamEntityList = contactUserModel.findBaseEntitys(map);
                break;
            case PAY_PLAN_TEAM:
                map.put("payPlanIdIn", dataIdList);
                userTeamEntityList = payPlanUserModel.findBaseEntitys(map);
                break;
            case REFUND_TEAM:
            case RETURN_TEAM:
                map.put("refundIdIn", dataIdList);
                userTeamEntityList = refundUserModel.findBaseEntitys(map);
                break;
            case WORK_ORDER_TEAM:
                map.put("workOrderIdIn", dataIdList);
                userTeamEntityList = workOrderFlowUserModel.findBaseEntitys(map);
                break;
            case PRODUCT_TEAM:
                map.put("dataIdIn", dataIdList);
                List<UserAndDepTeamEntity> userAndDepTeamEntityList = productUserModel.findBaseEntitys(map);
                userTeamEntityList = new ArrayList<>();
                for (UserAndDepTeamEntity userAndDepTeamEntity : userAndDepTeamEntityList) {
                    UserTeamEntity userTeamEntity = new UserTeamEntity();
                    BeanUtil.copyProperties(userAndDepTeamEntity, userTeamEntity);
                    userTeamEntity.setUserId(userAndDepTeamEntity.getRelationId());
                    userTeamEntity.setIsMain(userAndDepTeamEntity.getType() == 1 ? 0 : 1);
                    userTeamEntityList.add(userTeamEntity);
                }
                break;
            case COMPETITOR_TEAM:
                map.put("dataIn",dataIdList);
                List<CompetitorUserEntity> competitorUserEntityList = competitorUserModel.findBaseEntities(map);
                userTeamEntityList = new ArrayList<>();
                for (CompetitorUserEntity competitorUserEntity : competitorUserEntityList) {
                    UserTeamEntity userTeamEntity = new UserTeamEntity();
                    BeanUtil.copyProperties(competitorUserEntity,userTeamEntity);
                    userTeamEntity.setUserId(competitorUserEntity.getRelationId());
                    userTeamEntity.setIsMain(competitorUserEntity.getType() == 1 ? 0: 1);
                    userTeamEntityList.add(userTeamEntity);
                }
                break;
            case PAYMENT_SHEET_TEAM:
                map.put("paymentSheetIdIn", dataIdList);
                userTeamEntityList = paymentSheetUserModel.findBaseEntitys(map);
                break;
            case PAY_SHEET_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = payPlanSheetUserModel.findBaseEntitys(map);
                break;
            case CLUE_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = clueUserModel.findBaseEntitys(map);
                break;
            case MARKET_ACTIVITY_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = marketActivityUserModel.findBaseEntitys(map);
                break;
            case WAREHOUSE_TEAM:
                map.put("dataIdIn", dataIdList);
                // type=0时,relationId为员工Id
                map.put("type", BasicConstant.ZERO);
                List<WarehouseUserEntity> warehouseUserList = warehouseUserModel.findEntitys(map);
                for (WarehouseUserEntity entity : warehouseUserList){
                    UserTeamEntity userTeamEntity = new UserTeamEntity();
                    userTeamEntity.setUserId(entity.getRelationId());
                    userTeamEntity.setUserName(entity.getRelationName());
                    userTeamEntity.setDataId(entity.getDataId());
                    userTeamEntity.setId(entity.getId());
                    userTeamEntityList.add(userTeamEntity);
                }
                break;
            case PAAS_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = paasUserModel.findBaseEntitys(map);
                break;
            case PAYMENT_BALANCE_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = paymentBalanceUserModel.findBaseEntitys(map);
                break;
            case PAY_BALANCE_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = payBalanceUserModel.findBaseEntitys(map);
                break;
            case WORK_ORDER_V2_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = userTeamModel.findBaseEntitys(map, "tb_work_order_v2_user");
                break;
            case SLA_LOG_TEAM:
                map.put("dataIdIn",dataIdList);
                userTeamEntityList = userTeamModel.findBaseEntitys(map, "tb_sla_log_user");
                break;
            case SERVICE_PROJECT_TEAM:
                map.put("dataIdIn", dataIdList);
                List<UserAndDepTeamEntity> userAndDepTeamEntities = userAndDepTeamModel.findBaseEntitys(map, "tb_work_order_v2_service_project_user");
                userTeamEntityList = new ArrayList<>();
                for (UserAndDepTeamEntity userAndDepTeamEntity : userAndDepTeamEntities) {
                    UserTeamEntity userTeamEntity = new UserTeamEntity();
                    BeanUtil.copyProperties(userAndDepTeamEntity, userTeamEntity);
                    userTeamEntity.setUserId(userAndDepTeamEntity.getRelationId());
                    userTeamEntity.setIsMain(userAndDepTeamEntity.getType() == 1 ? 0 : 1);
                    userTeamEntityList.add(userTeamEntity);
                }
                break;
            case RECEIPT_ORDER_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = userTeamModel.findBaseEntitys(map, "tb_work_order_v2_receipt_order_user");
                break;
            default:
                return new ArrayList<>();
        }
        return userTeamEntityList;
    }

    /**
     * 负责展示处理
     * @param userIdList
     * @param dataIdList 业务数据idList
     * @param corpid 公司id
     * @param businessType 业务类型
     * @param isPublic 是否公海(有个前负责人逻辑
     * @param mainUserIdMap 负责人map
     * @param coUserIdMap 协同人map
     */
    public void getUserIdMapSetShow(Set<String> userIdList, List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Map<Long, List<String>> mainUserIdMap,
                                    Map<Long, List<String>> coUserIdMap, Integer del) {
        List<UserTeamEntity> userTeamEntityList = getUserTeamList(dataIdList, corpid, businessType, isPublic, del);

        for (UserTeamEntity entity : userTeamEntityList) {
            userIdList.add(entity.getUserId());
            if (Objects.equals(entity.getIsMain(),1)){
                if (mainUserIdMap.containsKey(entity.getDataId())) {
                    List<String> userId =  mainUserIdMap.get(entity.getDataId());
                    if (!userId.contains(entity.getUserId())) {
                        userId.add(entity.getUserId());
                    }
                    mainUserIdMap.put(entity.getDataId(), userId);
                } else {
                    List<String> userId = new ArrayList<>();
                    userId.add(entity.getUserId());
                    mainUserIdMap.put(entity.getDataId(), userId);
                }

            }else {
                if (coUserIdMap.containsKey(entity.getDataId())) {
                    List<String> userId =  coUserIdMap.get(entity.getDataId());
                    if (!userId.contains(entity.getUserId())) {
                        userId.add(entity.getUserId());
                    }
                    coUserIdMap.put(entity.getDataId(), userId);
                }else {
                    List<String> userId = new ArrayList<>();
                    userId.add(entity.getUserId());
                    coUserIdMap.put(entity.getDataId(), userId);
                }
            }
        }
    }

    public Map<Long, List<String>> coUserMapShow(Set<String> userIdSet, Collection<Long> formDataIdIn, String corpid) throws XbbException {
        Map<Long, List<String>> coUserMap;
        try {
            if (CollectionsUtil.isEmpty(formDataIdIn)) {
                return new HashMap<>(BasicConstant.ZERO);
            }
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(StringConstant.CORPID, corpid);
            map.put("dataIdIn", formDataIdIn);
            map.put("isMain", 0);
            map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<PaasUserEntity> list = paasUserModel.findEntitys(map);
            if(list == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            coUserMap = new HashMap<>(list.size());
            list.forEach(item->{
                if (coUserMap.containsKey(item.getDataId())) {
                    List<String> userList = coUserMap.get(item.getDataId());
                    userList.add(item.getUserId());
                    coUserMap.put(item.getDataId(), userList);
                } else {
                    List<String> userList = new ArrayList<>();
                    userList.add(item.getUserId());
                    coUserMap.put(item.getDataId(), userList);
                }
                userIdSet.add(item.getUserId());
            });
        } catch (XbbException e) {
            throw e;
        }  catch (Exception e) {
            LOG.error("coUser.coUserMap出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return coUserMap;
    }

    public void getVisableDepAndUser(Set<String> userIdList, String corpid,Long productId,List<String> visableDep,List<String> visableUser){
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.PRODUCT_ID, productId);
        param.put("del", 0);
        List<ProductUserEntity> productUserList = productUserModel.findEntitys(param);

        for (ProductUserEntity productUser : productUserList) {
            if (Objects.equals(productUser.getType(), 1)) {
                Long depId = StringUtil.StringToLong(productUser.getRelationId());
                if (Objects.equals(depId, 0L)) {
                    depId = 1L;
                }
                DepartmentEntity department = departmentModel.getByKey(depId, corpid);
                if (department != null) {
                    productUser.setUserName(department.getName());
                    visableDep.add(String.valueOf(department.getId()));
                }
            } else {
                UserEntity user = userModel.getByKey(productUser.getRelationId(), corpid);
                if (user == null) {
                    productUser.setUserName("");
                    productUser.setUserAvatar(ConfigConstant.DEFAULT_PIC);
                } else {
                    productUser.setUserName(user.getName());
                    productUser.setUserAvatar(StringUtil.isEmpty(user.getAvatar()) ? ConfigConstant.DEFAULT_PIC : user.getAvatar());
                    visableUser.add(String.valueOf(user.getUserId()));
                    userIdList.add(user.getUserId());
                }
            }
        }
    }

    public void getVisiableDepAndUser4ServiceProject(Set<String> userIdList, String corpid, Long serviceProjectId, List<String> visibleDep, List<String> visibleUser, Integer del) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("dataId", serviceProjectId);
        param.put("del", del);
        List<CommonVisibleRangeTeamEntity> serviceProjectUserList = userAndDepTeamModel.findEntitys(param, "tb_work_order_v2_service_project_user");

        for (CommonVisibleRangeTeamEntity serviceProjectUser : serviceProjectUserList) {
            if (Objects.equals(serviceProjectUser.getType(), 1)) {
                Long depId = StringUtil.StringToLong(serviceProjectUser.getRelationId());
                if (Objects.equals(depId, 0L)) {
                    depId = 1L;
                }
                DepartmentEntity department = departmentModel.getByKey(depId, corpid);
                if (department != null) {
                    serviceProjectUser.setUserName(department.getName());
                    visibleDep.add(String.valueOf(department.getId()));
                }
            } else {
                UserEntity user = userModel.getByKey(serviceProjectUser.getRelationId(), corpid);
                if (user == null) {
                    serviceProjectUser.setUserName("");
                    serviceProjectUser.setUserAvatar(ConfigConstant.DEFAULT_PIC);
                } else {
                    serviceProjectUser.setUserName(user.getName());
                    serviceProjectUser.setUserAvatar(StringUtil.isEmpty(user.getAvatar()) ? ConfigConstant.DEFAULT_PIC : user.getAvatar());
                    visibleUser.add(String.valueOf(user.getUserId()));
                    userIdList.add(user.getUserId());
                }
            }
        }
    }

    public void getCompetitorVisableDepAndUser(Set<String> userIdList, String corpid,Long dataId,List<String> visableDep,List<String> visableUser){
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("dataId", dataId);
        param.put("del", 0);
        List<CompetitorUserEntity> competitorUserList = competitorUserModel.findEntitys(param);

        Set<Long> depIdSet = new HashSet<>();
        Set<String> UserIdSet = new HashSet<>();
        for (CompetitorUserEntity competitorUser : competitorUserList) {
            if (Objects.equals(competitorUser.getType(), 1)) {
                Long depId = StringUtil.StringToLong(competitorUser.getRelationId());
                if (Objects.equals(depId, 0L)) {
                    depId = 1L;
                }
                depIdSet.add(depId);
            } else {
                UserIdSet.add(competitorUser.getRelationId());
            }
        }

        List<DepartmentEntity> departmentEntityList = departmentModel.getByDepIdIn(corpid, depIdSet);
        Map<Long,DepartmentEntity> departmentEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        departmentEntityList.forEach(item->{
            departmentEntityMap.put(item.getId(),item);
        });

        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, UserIdSet);
        Map<String,UserEntity> userEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userEntityList.forEach(item->{
            userEntityMap.put(item.getUserId(),item);
        });

        for (CompetitorUserEntity competitorUser : competitorUserList) {
            if (Objects.equals(competitorUser.getType(), 1)) {
                Long depId = StringUtil.StringToLong(competitorUser.getRelationId());
                if (Objects.equals(depId, 0L)) {
                    depId = 1L;
                }
                DepartmentEntity department = departmentEntityMap.get(depId);
                if (department != null) {
                    competitorUser.setUserName(department.getName());
                    visableDep.add(String.valueOf(department.getId()));
                }
            } else {
                UserEntity user = userEntityMap.get(competitorUser.getRelationId());
                if (user == null) {
                    competitorUser.setUserName("");
                    competitorUser.setUserAvatar(ConfigConstant.DEFAULT_PIC);
                } else {
                    competitorUser.setUserName(user.getName());
                    competitorUser.setUserAvatar(StringUtil.isEmpty(user.getAvatar()) ? ConfigConstant.DEFAULT_PIC : user.getAvatar());
                    visableUser.add(String.valueOf(user.getUserId()));
                    userIdList.add(user.getUserId());
                }
            }
        }
    }

}
